<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6" v-for="item in todos" :key="item._id">
        <el-card style="margin-top: 10px" :class="{ done: item.done }">
          <template #header>
            <div class="card-header swit">
              <span>{{ moment(item.pub_time).format('YYYY-MM-DD') }}</span>
              <el-switch v-model="item.done" @change="doneChange(item)" />
            </div>
          </template>
          <img :src="item.imageUrl" style="width: 100%; height: 200px; object-fit: cover" />
          <div style="margin-top: 10px">
            <span class="text item">{{ item.content }}</span>
            <el-tag style="margin-left: 10px" :type="item.done ? 'danger' : 'primary'">{{
              item.done ? '已做' : '未做'
            }}</el-tag>
          </div>
          <template #footer>
            <div class="footer">
              <el-button icon="Delete" @click="removeTodo(item._id)" round>删除</el-button>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup name="">
import moment from 'moment'
import { onMounted, ref } from 'vue'
import type { TodoData } from './types'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

let todos = ref<TodoData[]>([])

const getTodos = async () => {
  let result = await request.get('/todo')
  console.log(result)
  todos.value = result.data.data
}

onMounted(() => {
  getTodos()
})

const doneChange = async (item: TodoData) => {
  let result = await request.put('/todo/' + item._id, {
    done: item.done
  })
  if (result.data.code == '0000') {
    ElMessage.success('数据更新成功')
    getTodos()
  } else {
    ElMessage.error('数据更新失败')
  }
}

const removeTodo = async (id: string) => {
  let result = await request.delete('/remove/todo/' + id)
  if (result.data.code == '0000') {
    ElMessage.success('数据删除成功')
    getTodos()
  } else {
    ElMessage.error('数据删除失败')
  }
}
</script>

<style scoped>
.container {
  padding: 30px;
}

.swit {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.done {
  background: #bcf;
}

.footer {
  display: flex;
  justify-content: end;
}
</style>
